<?php
// 测试数据库操作

echo "测试数据库操作...\n";

// 从.env文件读取数据库信息
$envFile = '.env';
if (file_exists($envFile)) {
    $envContent = file_get_contents($envFile);
    preg_match('/database\s*=\s*(\w+)/', $envContent, $dbMatches);
    preg_match('/username\s*=\s*(\w+)/', $envContent, $userMatches);
    preg_match('/password\s*=\s*(\w+)/', $envContent, $passMatches);
    
    $dbname = $dbMatches[1] ?? 'yingyang';
    $username = $userMatches[1] ?? 'root';
    $password = $passMatches[1] ?? 'root';
    
    try {
        $pdo = new PDO("mysql:host=127.0.0.1;dbname={$dbname};charset=utf8mb4", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        // 测试查询未处理的菜品
        echo "1. 测试查询未处理的菜品...\n";
        $stmt = $pdo->prepare("SELECT id, name FROM fa_food_dish WHERE ai_called = 0 LIMIT 10");
        $stmt->execute();
        $dishes = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo "未处理菜品数量: " . count($dishes) . "\n";
        if (!empty($dishes)) {
            foreach ($dishes as $dish) {
                echo "- ID: " . $dish['id'] . ", 名称: " . $dish['name'] . "\n";
            }
        }
        
        // 测试获取食材信息
        echo "\n2. 测试获取食材信息...\n";
        $stmt = $pdo->prepare("SELECT id, name FROM fa_food_ingredient LIMIT 5");
        $stmt->execute();
        $ingredients = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo "食材数量: " . count($ingredients) . "\n";
        foreach ($ingredients as $ingredient) {
            echo "- ID: " . $ingredient['id'] . ", 名称: " . $ingredient['name'] . "\n";
        }
        
        // 测试更新操作（使用第一个菜品）
        if (!empty($dishes)) {
            $firstDish = $dishes[0];
            echo "\n3. 测试更新菜品ID " . $firstDish['id'] . "...\n";
            
            // 开始事务
            $pdo->beginTransaction();
            try {
                // 更新菜品信息
                $stmt = $pdo->prepare("UPDATE fa_food_dish SET ai_called = 1, cook_time = ?, steps = ?, updatetime = ? WHERE id = ?");
                $result = $stmt->execute(['测试时间', '测试步骤', time(), $firstDish['id']]);
                echo "更新菜品结果: " . ($result ? '成功' : '失败') . "\n";
                
                // 删除原有的食材关联
                $stmt = $pdo->prepare("DELETE FROM fa_food_ingredientrel WHERE dish_id = ?");
                $stmt->execute([$firstDish['id']]);
                echo "删除原有食材关联\n";
                
                // 添加测试食材关联
                $stmt = $pdo->prepare("INSERT INTO fa_food_ingredientrel (dish_id, ingredient_id, quantity, createtime, weigh) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$firstDish['id'], 1, '100g', time(), 1]);
                echo "添加测试食材关联\n";
                
                // 提交事务
                $pdo->commit();
                echo "事务提交成功\n";
                
                // 回滚更改以便重复测试
                $pdo->beginTransaction();
                $stmt = $pdo->prepare("UPDATE fa_food_dish SET ai_called = 0, cook_time = '', steps = '' WHERE id = ?");
                $stmt->execute([$firstDish['id']]);
                $stmt = $pdo->prepare("DELETE FROM fa_food_ingredientrel WHERE dish_id = ?");
                $stmt->execute([$firstDish['id']]);
                $pdo->commit();
                echo "回滚更改完成\n";
                
            } catch (\Exception $e) {
                $pdo->rollback();
                echo "事务失败: " . $e->getMessage() . "\n";
            }
        }
        
    } catch (\Exception $e) {
        echo "数据库操作错误: " . $e->getMessage() . "\n";
    }
} else {
    echo "未找到.env配置文件\n";
}

echo "\n测试完成\n";
?>